package org.vectrics.user.web.struts;

import java.util.Properties;
import org.vectrics.common.html.*;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.VectricsTagSupport;
import org.vectrics.user.*;
import org.apache.log4j.*;
import org.vectrics.common.view.*;
import org.vectrics.user.web.struts.SaveUserAction;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

/**
 *  Description of the Class
 *
 *@author     mmoore
 *@created    December 24, 2002
 */
public abstract class UserEditTag extends VectricsTagSupport {

	private static final long serialVersionUID = -8811100040426891039L;

	private static Category log = Category.getInstance(UserEditTag.class);
    public static String CANDIDATE_PARAM = "candidate";
    private Properties roles = new Properties();
	private String contextPath = null;


    public UserEditTag() { }


	protected String getContextPath() {
		return(contextPath);
	}
	
	public String makeStartTag()  {
        log.info("doStartTag() called");
        /*
		
		ServletRequest request = super.pageContext.getRequest();
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		contextPath = httpRequest.getContextPath();
		HttpSession session = super.pageContext.getSession();
		
		//UserProfileForm profileForm = (UserProfileForm)session.getAttribute("userProfileForm");
		ActionErrors errors = null;
		try {
			errors = RequestUtils.getActionErrors(pageContext, Globals.ERROR_KEY);
		} catch (JspException e) {
			RequestUtils.saveException(pageContext, e);
			throw e;
		}		
		pageContext.setAttribute(Constants.FORM_KEY, this, PageContext.REQUEST_SCOPE);

		Properties params = new NullableProperties();
		Properties invalidParams = null;
        String performLoginParam = params.getProperty(SaveUserAction.PERFORM_LOGIN_PARAM);
        String enterContactParam = params.getProperty(SaveUserAction.ENTER_CONTACT_INFO_PARAM);

        Table mainTable = new Table();
        Row mainRow = mainTable.addRow();
        Cell mainCell = mainRow.addCell();
        if ((invalidParams != null) && (invalidParams.isEmpty() == false)) {
        	mainCell.addElement(TextHelper.getFont("errorFont", "The following fields were improperly entered:<br>"));
        	while (invalidParams.keys().hasMoreElements()) {
        		String name = (String)invalidParams.keys().nextElement();
        		String value = invalidParams.getProperty(name); 
				mainCell.addElement(TextHelper.getFont("errorFont", value));
        	}
        }

        boolean authorized = true;
        User appUser = getUserToEdit(request, params, invalidParams);
        ContactInfo contactInfo = null;
        

        if (authorized) {
            SimpleForm form = new SimpleForm(params, invalidParams);
            if (log.isDebugEnabled()) {
                if (appUser == null) {
                    log.debug("doRender() - new user");
                }
                else {
                    log.debug("doRender() - appUser = " + appUser.toString());
                }
            }

            if ((invalidParams == null) || (invalidParams.size() <= 0)) {
                log.debug("doRender() - creating temporary params for user information.");

                log.debug("doRender() - finding information about user...");
                if (appUser == null) {
                    form.addHidden(SaveUserAction.NEW_USER_PARAM, "true");
                }
                else {
                	log.debug("doRender() - setting form values for core user properties");
                	log.debug("doRender() - user name = " + appUser.getName());
					params.setProperty(SaveUserAction.USER_NAME_PARAM, appUser.getUserName());
					params.setProperty(SaveUserAction.USER_ID_PARAM, appUser.getId());
                    params.setProperty(SaveUserAction.LAST_NAME_PARAM, appUser.getLastName());
					params.setProperty(SaveUserAction.FIRST_NAME_PARAM, appUser.getFirstName());
					params.setProperty(SaveUserAction.MIDDLE_NAME_PARAM, appUser.getMiddleName());
					params.setProperty(SaveUserAction.PASSWORD_PARAM, appUser.getPassword());
					params.setProperty(SaveUserAction.PREFIX_PARAM, appUser.getNamePrefix());
					params.setProperty(SaveUserAction.GENDER_PARAM, appUser.getGender());
					params.setProperty(SaveUserAction.MARITAL_STATUS_PARAM, appUser.getMaritalStatus());
					params.setProperty(SaveUserAction.KNOWN_AS_PARAM, appUser.getKnownAs());
					params.setProperty(SaveUserAction.PASSWORD_2_PARAM, appUser.getPassword());
					log.debug("doRender() - setting form values for core user properties 6");

					log.debug("doRender() - getting contact info...");
					contactInfo = appUser.getContactInfo();
                    if (contactInfo != null) {
                        log.debug("doRender() - setting contact info params");
						params.setProperty(SaveUserAction.EMAIL_PARAM, appUser.getContactInfo().getEMail());
						params.setProperty(SaveUserAction.EMAIL_2_PARAM, appUser.getContactInfo().getEMail2());
						params.setProperty(SaveUserAction.WORK_PHONE_PARAM, appUser.getContactInfo().getWorkPhone());
						params.setProperty(SaveUserAction.HOME_PHONE_PARAM, appUser.getContactInfo().getHomePhone());
						params.setProperty(SaveUserAction.CELL_PHONE_PARAM, appUser.getContactInfo().getCellPhone());
                    }

					readUserPrivileges(appUser, params);
                    
                    if (contactInfo != null) {
                        log.debug("doRender() - finding home address params");
                        Address homeAddress = contactInfo.getHomeAddress();
                        if (homeAddress != null) {
							params.setProperty(SaveUserAction.HOME_ADDRESS_1_PARAM, homeAddress.getAddress1());
							params.setProperty(SaveUserAction.HOME_ADDRESS_2_PARAM, homeAddress.getAddress2());
							params.setProperty(SaveUserAction.HOME_CITY_PARAM, homeAddress.getCity());
							params.setProperty(SaveUserAction.HOME_STATE_PARAM, homeAddress.getState());
							params.setProperty(SaveUserAction.HOME_ZIP_PARAM, homeAddress.getPostalCode());
							params.setProperty(SaveUserAction.HOME_COUNTRY_PARAM, homeAddress.getPostalCode());
                        }
                        
                        log.debug("deRender() - finding work address fields");
                        Address workAddress = contactInfo.getWorkAddress();
                        if (workAddress != null) {
							params.setProperty(SaveUserAction.WORK_ADDRESS_1_PARAM, workAddress.getAddress1());
							params.setProperty(SaveUserAction.WORK_ADDRESS_2_PARAM, workAddress.getAddress2());
							params.setProperty(SaveUserAction.WORK_CITY_PARAM, workAddress.getCity());
							params.setProperty(SaveUserAction.WORK_STATE_PARAM, workAddress.getState());
							params.setProperty(SaveUserAction.WORK_ZIP_PARAM, workAddress.getPostalCode());
							params.setProperty(SaveUserAction.WORK_COUNTRY_PARAM, workAddress.getPostalCode());
                        }
                    }

                }
            }
            else {
                log.debug("doRender() - request has invalid params, assuming that this form is being shown to fix bad submission.");
            }

            log.debug("doRender() - creating entry form.");
            form.showInvalidParams();
            mainCell.addElement(form);

			log.debug("doRender() - setting form action.");
            form.setAction(getFormAction(httpRequest));
            
			try {
            	makeForm(request,  params, invalidParams, appUser, form);
			}
			catch (Exception ex) {
				log.error("Exception in makeForm()", ex);
				throw new JspException(ex);
			}

        }
        else {
            invalidParams.setProperty("", "You are not authorized to edit this user.");
        }


		JspWriter writer = pageContext.getOut();
		try {
			writer.print(mainTable.toString());
		}
		catch (IOException ex) {
			throw new JspException("IOException attempting to write tag to output. " + ex.getMessage());
		}
		*/
		return("");
    }

    /**
     *  Gets the showRoles attribute of the UserEditTag object
     *
     *@param  request  Description of the Parameter
     *@return          The showRoles value
     */
    protected boolean getShowRoles(ServletRequest request) {
        boolean showRoles = false;
        if (request.getParameter("show_roles") != null) {
            showRoles = true;
        }
        return (showRoles);
    }
    protected void makeMainSectionEnd(Person person, ServletRequest request, SimpleForm form) {
    }


    /**
     *  Adds a feature to the Role attribute of the UserEditTag object
     *
     *@param  description  The feature to be added to the Role attribute
     *@param  role         The feature to be added to the Role attribute
     */
    protected void addRole(String description, String role) {
        roles.setProperty(role, description);
    }


    /**
     *  Gets the formAction attribute of the UserEditTag object
     *
     *@param  request  Description of the Parameter
     *@return          The formAction value
     */
    protected abstract String getFormAction(HttpServletRequest request);


    /**
     *  Gets the vectricsAction attribute of the UserEditTag object
     *
     *@param  request  Description of the Parameter
     *@return          The vectricsAction value
     */
    protected String getVectricsAction(ServletRequest request) {
        return (getContextPath() + SaveUserAction.SAVE_USER_ACTION);
    }



    /**
     *  Gets the showPassword attribute of the UserEditTag object
     *
     *@param  request  Description of the Parameter
     *@return          The showPassword value
     */
    protected boolean getShowPassword(ServletRequest request) {
        boolean showPassword = false;
        if (request.getParameter("show_password") != null) {
            showPassword = true;
        }
        return (showPassword);
    }
/*
    protected boolean getEnterHomeAddress(ServletRequest request) {
        boolean result = false;
        String addrParam = request.getParameter(SaveUserAction.ENTER_HOME_ADDRESS_PARAM);
        if (addrParam != null) {
            result = true;
        }
        return(result);
    }
    
    protected boolean getEnterWorkAddress(ServletRequest request) {
        boolean result = false;
        String addrParam = request.getParameter(SaveUserAction.ENTER_WORK_ADDRESS_PARAM);
        if (addrParam != null) {
            result = true;
        }
        return(result);
    }

    protected boolean getShowKnownAs(ServletRequest request) {
        boolean result = false;
        String addrParam = request.getParameter(SaveUserAction.ENTER_KNOWN_AS_PARAM);
        if (addrParam != null) {
            result = true;
        }
        return(result);
    }

    protected boolean getShowPrefix(ServletRequest request) {
        boolean result = false;
        String addrParam = request.getParameter(SaveUserAction.ENTER_PREFIX_PARAM);
        if (addrParam != null) {
            result = true;
        }
        return(result);
    }
	protected boolean getAllowUserNameEdit() {
		return(false);	
	}
	
    protected boolean getShowGender(ServletRequest request) {
        boolean result = false;
        String addrParam = request.getParameter(SaveUserAction.ENTER_GENDER_PARAM);
        if (addrParam != null) {
            result = true;
        }
        return(result);
    }

    protected boolean getShowMaritalStatus(ServletRequest request) {
        boolean result = false;
        String addrParam = request.getParameter(SaveUserAction.ENTER_MARITAL_STATUS_PARAM);
        if (addrParam != null) {
            result = true;
        }
        return(result);
    }

    
    protected void makeFormEnd(User user, ServletRequest request, Properties params, Properties invalidParams, SimpleForm form) {
        // Nothing - override to change
    }


    protected void makeForm(ServletRequest request, Properties params, Properties invalidParams, User user, SimpleForm form) {
        log.debug("makeForm()");

        String performLoginParam = request.getParameter(SaveUserAction.PERFORM_LOGIN_PARAM);
        String enterContactParam = request.getParameter(SaveUserAction.ENTER_CONTACT_INFO_PARAM);
        String candidateParam = request.getParameter(CANDIDATE_PARAM);

        boolean showRoles = getShowRoles(request);

        boolean showUserGroups = false;
        if (request.getParameter("show_groups") != null) {
            showUserGroups = true;
        }

        if (performLoginParam != null) {
            log.debug("makeForm() - login param passed.  User will be logged in if edit fields are valid.");
            form.addHidden(SaveUserAction.PERFORM_LOGIN_PARAM, "true");
        }

        boolean showPassword = getShowPassword(request);

        Table bigTable = new Table();
        bigTable.setWidth(800);
        form.addElement(bigTable);
        Row row = bigTable.addRow();
        Cell formLeftCell = row.addCell();
        formLeftCell.setWidth("50%");
        Cell formBlankCell = row.addCell();
        formBlankCell.setWidth(50);
        Cell formRightCell = row.addCell();
        formRightCell.setWidth("50%");

        Table leftTable = new Table();
        formLeftCell.addElement(leftTable);

        Table rightTable = new Table();
        formRightCell.addElement(rightTable);

        form.setTable(leftTable);
                
        log.debug("makeForm() - adding user name fields to form.");
        if ((user == null) || (getAllowUserNameEdit())) {
            form.makeEditRow(SaveUserAction.USER_NAME_PARAM, "User Name", true);
            form.addBlankRow();
        }
        else {
            form.makeLabelRow("User", user.getUserName());
            form.addBlankRow();
        }
		form.addHidden(SaveUserAction.USER_ID_PARAM, user.getId());

        log.debug("makeForm() - adding password fields to form.");
        if (getShowPassword(request)) {
            form.makePasswordEditRow(SaveUserAction.PASSWORD_PARAM, "Password", true);
            form.addBlankRow();
            form.makePasswordEditRow(SaveUserAction.PASSWORD_2_PARAM, "Confirm Password", true);
            form.addBlankRow();
        }

        Input edit = form.makeEditRow(SaveUserAction.FIRST_NAME_PARAM, "First Name", true);
        form.addBlankRow();
        form.makeEditRow(SaveUserAction.LAST_NAME_PARAM, "Last Name", true);
        
        if (getShowKnownAs(request)) {
            form.addBlankRow();
            form.makeEditRow(SaveUserAction.KNOWN_AS_PARAM, "Known As", false);
        }
        
        if (getShowPrefix(request)) {
            form.addBlankRow();
            form.makeEditRow(SaveUserAction.PREFIX_PARAM, "Prefix", false);
        }
        
        if (getShowMaritalStatus(request)) {
            form.addBlankRow();
            form.addComboRow("Marital Status", SaveUserAction.MARITAL_STATUS_PARAM, 
                    makeMaritalStatusCombo(user), false);
        }
        
        if (getShowGender(request)) {
            form.addBlankRow();
            form.addComboRow("Gender", SaveUserAction.GENDER_PARAM, 
                    makeGenderCombo(user), false);
        }
        
        form.addBlankRow();
        form.makeEditRow(SaveUserAction.EMAIL_PARAM, "Primary E-Mail", true);
        form.addBlankRow();
        form.makeEditRow(SaveUserAction.EMAIL_2_PARAM, "Secondary E-Mail", false);
        form.addBlankRow();
        form.makeEditRow(SaveUserAction.WORK_PHONE_PARAM, "Work Phone", false);
        form.addBlankRow();
        form.makeEditRow(SaveUserAction.HOME_PHONE_PARAM, "Home Phone", false);
        form.addBlankRow();
        form.makeEditRow(SaveUserAction.CELL_PHONE_PARAM, "Mobile Phone", false);
        form.addBlankRow();
        
        log.debug("makeForm() - displaying addresses");
        if (getEnterHomeAddress(request)) {
            makeAddressEntry("Home Address", "home_", form);
        }
        
        if (getEnterWorkAddress(request)) {
            makeAddressEntry("Work Address", "work_", form);
        }
        
        
        makeMainSectionEnd(user, request, form);
        
        if (candidateParam != null) {

        }

        log.debug("makeForm() - adding role fields to form.");
        if (showRoles) {
            form.setTable(rightTable);
            makeRoleSection(form, user);
        }

        makeFormEnd(user, request, params, invalidParams, form);

        row = bigTable.addRow();
        Cell cell = row.addCell();
        cell.setColSpan(3);
        Table bottomTable = new Table();
        cell.addElement(bottomTable);

        form.setTable(bottomTable);
        form.addSubmitButton("Submit", "Cancel");

        log.debug("makeForm() - done.");
    }
*/

    protected Person getUserToEdit(ServletRequest request, Properties params, Properties invalidParams) throws JspException {
    	HttpServletRequest httpRequest = (HttpServletRequest)request;
    	Person authUser = this.getAuthPerson();

    	Person appUser = null;
        log.debug("getUserToEdit() - called");
        String newUserParam = request.getParameter(SaveUserAction.NEW_USER_PARAM);
        
        if (newUserParam != null) {
        	log.debug("getUserToEdit() - new user was specified by parameter, returning user = NULL");
        	appUser = null;	
        }
        else {
	        String userId = request.getParameter("user");
	        if (userId == null) {
	        	Person user = authUser;
	        	userId = user.getId().toString();
	        }
	
			log.debug("getUserToEdit() - getting user: " + userId);
			try {
				appUser = CoreServiceLocator.getPersonService().findPersonById(new Long(userId));
			}
			catch (org.vectrics.DataException de) {
				log.error("DataException finding user to edit", de);
			}
	        
	        
	        try {
	            if ((newUserParam == null) || (newUserParam.length() == 0)) {
	                params.setProperty("user", userId);
	                try {
	                    if (userId != null) {
	                    }
	                    else {
	                    	appUser = new Person();
	                    }
	                }
	                catch (Exception ex) {
	                    log.error("getUserToEdit() - exception finding/creating user.", ex);
	                }
	            }
	            else {
	                log.debug("getUserToEdit() - creating new user");
	            }
	        }
	        catch (Exception ex) {
	            log.error("Exception finding or creating user.", ex);
	        }
        }

        return (appUser);
    }



    
    protected void makeAddressEntry(String caption, String paramPrefix, SimpleForm form) {
        log.debug("makeAddressEntry() called");
        
        form.addSection(caption, null);
        form.addHidden(paramPrefix + "addr_enter", "true");
        form.makeEditRow(paramPrefix + "Address1", "Address", false);
        form.addBlankRow();
        form.makeEditRow(paramPrefix + "Address2", "Address 2", false);
        form.addBlankRow();
        form.makeEditRow(paramPrefix + "City", "City", false);
        form.addBlankRow();
        form.makeEditRow(paramPrefix + "State", "State", false);
        form.addBlankRow();
        form.makeEditRow(paramPrefix + "PostalCode", "Zip", false);
        form.addBlankRow();
    }

    
    
    
    Combo makeGenderCombo(Person user) {
        Combo combo = new Combo();
        combo.setStyle("width:250;font-family:verdana,arial,sans serif;font-size=" +
        		"11px");
        combo.addOption("", "");
        combo.addOption("Male", "m");
        combo.addOption("Female", "f");
       //combo.setMultiple(true);
       if (user != null) {
           combo.selectOption("" + user.getGender());
       }
        
        return(combo);
    }

    
    Combo makeMaritalStatusCombo(Person user) {
        Combo combo = new Combo();
        combo.setStyle("width:250;font-family:verdana,arial,sans serif;font-size=" +
        		"11px");
        combo.addOption("", "");
        combo.addOption("Married", "m");
        combo.addOption("Single", "s");
        combo.addOption("Divorced", "d");
       if (user != null) {
           combo.selectOption("" + user.getMaritalStatus());
       }
        
        return(combo);
    }

    
    /**
     *  Description of the Method
     *
     *@param  form  Description of the Parameter
     *@param  user  Description of the Parameter
     */
    private void makeRoleSection(SimpleForm form, User user) {
    	/*
    	log.debug("makeRoleSelection() called");
        if (roles.size() > 0) {
            form.addSection("User Roles", null);
            form.addHidden(SaveUserAction.ROLES_ENTERED, "true");

            Enumeration propNames = this.roles.propertyNames();
            while (propNames.hasMoreElements()) {
                String name = (String) propNames.nextElement();
                String desc = roles.getProperty(name);
                Input checkBox = new Input();
                checkBox.setType(Input.checkbox);

                if ((user != null) && (user.hasRole(name))) {
                    checkBox.setChecked(true);
                }
                else {
                    checkBox.setChecked(false);
                }
                checkBox.setName(name);
                form.addInputRow(desc, "ROLE_" + name, checkBox, false);
            }
        }
        else {
			log.debug("makeRoleSelection() - role list is empty.");
        }
        */
    }

}

